package point

import (
	"bufio"
	"os/exec"
	"strings"
)

type WanXGatewayPoint struct {
	index int
}

var wanxGateway string

func NewWanXGatewayPoint() *WanXGatewayPoint { return &WanXGatewayPoint{} }

func (s *WanXGatewayPoint) Get() any {
	var interfaceName string

	if s.index == 0 {
		interfaceName = "eth1"
	} else if s.index == 1 {
		interfaceName = "eth2"
	} else {
		return ""
	}

	getGatewayByInterfaceName := func(iface string) string {
		cmd := exec.Command("ip", "route")
		output, err := cmd.Output()
		if err != nil {
			return ""
		}

		scanner := bufio.NewScanner(strings.NewReader(string(output)))
		for scanner.Scan() {
			line := scanner.Text()
			if strings.Contains(line, iface) {
				fields := strings.Fields(line)
				if len(fields) >= 3 && fields[0] == "default" {
					return fields[2]
				}
			}
		}

		return ""
	}

	return getGatewayByInterfaceName(interfaceName)
}

func (s *WanXGatewayPoint) Set(val ...any) bool {
	if len(val) < 1 {
		return false
	}

	if gateway, ok := val[0].(string); ok {
		wanxGateway = gateway
	}

	return true
}

func (s *WanXGatewayPoint) SetRoute(str string) PointInterface {
	s.index = int(str[len("wan")]) - '0'
	return s
}
